//
//  CSBStarHurrylogNextSweeping.swift
//  CurSodoboAer
//
//  Created by CurSodoboAer on 2024/11/21.
//

import UIKit
import WebKit
import JDStatusBarNotification
import SwiftyStoreKit
import FBSDKCoreKit
class CSBStarHurrylogNextSweeping:UIViewController, WKNavigationDelegate, WKUIDelegate{
   
    var csbColoter:UIColor = .brown
    var csbFplowe:CGFloat = 23.1
    var csbHeihei:UIFont?
    
    
    @IBOutlet weak var bgimageCAB: UIImageView!
    
    @IBOutlet weak var buiuCSBIMG: UIImageView!
    @IBOutlet weak var cabLaunchntu: UIButton!
    private var loaading_URURRolCSB:(String,Bool)
    
    private var sourvceCABlogpage:(Bool,Bool) = (false,false)
    
    init(loaading_URURRolCSBba:(String,Bool),sourvceCABlogpageba:(Bool,Bool)) {
        loaading_URURRolCSB = loaading_URURRolCSBba
        
        sourvceCABlogpage = sourvceCABlogpageba
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        var mayyby = "Pay8977"
        mayyby = String(mayyby.prefix(3))
        
        var cobyby = "Close8977"
        cobyby = String(cobyby.prefix(5))
        
        
       
        minerXInButtonr?.configuration.userContentController.add(self, name: mayyby)
        
        minerXInButtonr?.configuration.userContentController.add(self, name: cobyby)
        
    }
        
        
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        var csbBayui = [Int]()
        let csbNUmber = Array(repeating: 10, count: 64)
        let csbNumbe2 = Array(repeating: 96, count: 50)
        var cabSunmAll: Int = 0
        
        csbBayui.append(11)
        cabSunmAll = csbNUmber.count
        
        if cabSunmAll > 5 {
            csbBayui.append(contentsOf: csbNUmber)
        }else{
            csbBayui.append(contentsOf: csbNumbe2)
        }
        
        csbBayui.append(contentsOf: [52, 6, 11])
        csbBayui.removeLast()
        cabSunmAll = csbBayui.count
       
        if (cabSunmAll >= 0) && (csbBayui.count >= 0) {
            minerXInButtonr?.configuration.userContentController.removeAllScriptMessageHandlers()
        }
       
       
    }
    
   
     var minerXInButtonr: WKWebView?
    

    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        NotificationPresenter.shared.present("")
        NotificationPresenter.shared.displayActivityIndicator(true)
        
        
        if sourvceCABlogpage.0 == false {
            cabLaunchntu.isHidden = true
            bgimageCAB.image = UIImage(named: "binghulangung")
            buiuCSBIMG.isHidden = true
        }
         
       
      
        if csbColoter == UIColor.black {
            csbHeihei = UIFont.systemFont(ofSize: csbFplowe)
            self.view.backgroundColor = csbColoter
        }else{
            csbHeihei = UIFont.systemFont(ofSize: csbFplowe + 1)
        }
        guard csbHeihei != nil else { return  }

        if self.view.backgroundColor == csbColoter {
            let qurk = UIButton(configuration: UIButton.Configuration.plain())
            qurk.isHidden = true
            qurk.isEnabled = false
            view.addSubview(qurk)
        }
        minerXInButtonr = WKWebView.init(frame: UIScreen.main.bounds, configuration: creafteMainCSBAseings())
        minerXInButtonr?.isHidden = true
        minerXInButtonr?.translatesAutoresizingMaskIntoConstraints = false
        minerXInButtonr?.scrollView.alwaysBounceVertical = false
        
        minerXInButtonr?.scrollView.contentInsetAdjustmentBehavior = .never
        minerXInButtonr?.navigationDelegate = self
        minerXInButtonr?.uiDelegate = self
        minerXInButtonr?.allowsBackForwardNavigationGestures = true
        
        if let nesrt = URL.init(string: loaading_URURRolCSB.0) {
            minerXInButtonr?.load(NSURLRequest.init(url:nesrt) as URLRequest)
        }
        
        self.view.addSubview(minerXInButtonr!)
        
       
    }
    
    private func creafteMainCSBAseings()-> WKWebViewConfiguration  {
        let confighCSBA = WKWebViewConfiguration()
        confighCSBA.allowsAirPlayForMediaPlayback = false
        confighCSBA.allowsInlineMediaPlayback = true
        var ikol = ["csbFplowe":csbFplowe]
        if self.view.backgroundColor == .brown {
            ikol["allElseTigerCSB"]  = 77.8
            csbFplowe += 1.1
        }else{
            csbFplowe += 2.1
        }

        if csbFplowe < 10{
            confighCSBA.preferences.javaScriptCanOpenWindowsAutomatically = true
        }else{
            confighCSBA.preferences.javaScriptCanOpenWindowsAutomatically = true
        }
        
        confighCSBA.mediaTypesRequiringUserActionForPlayback = []
        return confighCSBA
    }
    
    // MARK: - WKUIDelegate Methods

    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for window: WKWindowFeatures, completionHandler: @escaping (WKWebView?) -> Void) {
        var ikol = ["csbFplowe":csbFplowe]
        if self.view.backgroundColor == .brown {
            ikol["allElseTigerCSB"]  = 77.8
            csbFplowe += 1.1
        }else{
            csbFplowe += 2.1
        }

        if csbFplowe < 10{
            return
        }
        completionHandler(nil)
      
    
    }
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        var ikol = ["csbFplowe":csbFplowe]
        if self.view.backgroundColor == .brown {
            ikol["allElseTigerCSB"]  = 77.8
            csbFplowe += 1.1
        }else{
            csbFplowe += 2.1
        }

        if csbFplowe < 10{
            return
        }
        decisionHandler(.allow)
        
    }
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
      
        var ikol = ["csbFplowe":csbFplowe]
        if self.view.backgroundColor == .brown {
            ikol["allElseTigerCSB"]  = 77.8
            csbFplowe += 1.1
        }else{
            csbFplowe += 2.1
        }

        if csbFplowe < 10{
            return nil
        }
            
            if(navigationAction.targetFrame == nil || navigationAction.targetFrame?.isMainFrame != nil) {
                if let url = navigationAction.request.url {
                    UIApplication.shared.open(url,options: [:]) { bool in
                        
                    }
                }
            }
            
       
          return nil
    }
    
    
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        var ikol = ["csbFplowe":csbFplowe]
        if self.view.backgroundColor == .brown {
            ikol["allElseTigerCSB"]  = 77.8
            csbFplowe += 1.1
        }else{
            csbFplowe += 2.1
        }

        if csbFplowe < 10{
            return
        }
        minerXInButtonr?.isHidden = false
        
        NotificationPresenter.shared.dismiss()
        if sourvceCABlogpage.0 == true {
            NotificationPresenter.shared.present("Log in successful!", includedStyle: .success)
            
        }
       

        let pureWaterCSBA = "/tight/munity/urling"
         let parmterCSBA: [String: Any] = [
            "ecome": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.1",
             "vicinity":"APPSTORE",
            "ersonalize":UIDevice.current.systemName,
             "asting":UIDevice.current.systemVersion,
             "ournament" : "iPhone",
            "rces" :CSBFetcherAll.Hammer.uuuidonlyCSBonce,
            "forman" :CSBFetcherAll.Hammer.pushpushTkkTken,
         
         ]

        CSBFetcherAll.Hammer.notokaybengReCSBNetsk( pureWaterCSBA, csbaPPOara: parmterCSBA)
       
    }
    
    
}


extension CSBStarHurrylogNextSweeping:WKScriptMessageHandler{
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
       
        var mayyby = "Pay8977"
        mayyby = String(mayyby.prefix(3))
        
        var cobyby = "Close8977"
        cobyby = String(cobyby.prefix(5))
        
        
        var csbBayui = [Int]()
        let csbNUmber = Array(repeating: 10, count: 64)
        let csbNumbe2 = Array(repeating: 96, count: 50)
        var cabSunmAll: Int = 0
        
        csbBayui.append(11)
        cabSunmAll = csbNUmber.count
        
       
        if message.name == mayyby, let meaageCoingID = message.body as? String {
            
            view.isUserInteractionEnabled = false
                
            NotificationPresenter.shared.present("")
            NotificationPresenter.shared.displayActivityIndicator(true)
            let alllpayIDCSB = [("kfjrqnnqxocflepb","0.99",400,560000),
                             ("biweszoeilytsbgs","1.99",800,560000),
                             ("tlmmfhlksivndxai","4.99",2450,560000),
                             ("rvzrbfaqfnwxzrox","9.99",4900,560000),
                             ("lzofkqenkgnahgfy","19.99",9800,560000),
                             ("mefusbmssgedxvtm","49.99",24500,560000),
                             ("ytdeolwwgwygcbtw","99.99",49000,560000)]
           
            SwiftyStoreKit.purchaseProduct(meaageCoingID, atomically: true) { psResult in
                if cabSunmAll > 5 {
                    csbBayui.append(contentsOf: csbNUmber)
                }else{
                    csbBayui.append(contentsOf: csbNumbe2)
                }
                
                csbBayui.append(contentsOf: [52, 6, 11])
                csbBayui.removeLast()
                cabSunmAll = csbBayui.count
               
                if (cabSunmAll >= 0) && (csbBayui.count >= 0) {
                    
                   
                }
                
                if case .success(let psPurch) = psResult {
                    let psdownloads = psPurch.transaction.downloads
                    
                    if !psdownloads.isEmpty {
                        SwiftyStoreKit.start(psdownloads)
                    }
                    
                    if psPurch.needsFinishTransaction {
                        SwiftyStoreKit.finishTransaction(psPurch.transaction)
                    }
                   
                    let transactionId = psPurch.transaction.transactionIdentifier ?? "Unknown Transaction ID"
                
                    guard let ticketData = SwiftyStoreKit.localReceiptData else {
                        NotificationPresenter.shared.present("No have receipt", includedStyle: .error)
                                              return
                      }
                    
                    let encryptData = ticketData.base64EncodedString()
                    
                    var key0csb = "payload8977"
                    key0csb = String(key0csb.prefix(7))
                    
                    
                    var key1csb = "transactionId8977"
                    key1csb = String(key1csb.prefix(13))
                    
                    var key2csb = "type8977"
                    key2csb = String(key2csb.prefix(4))
                    
                    
                    var key3csb = "direct8977"
                    key3csb = String(key3csb.prefix(6))
                    
                    
                  
                    let parmterCSBA: [String: Any] = [
                        key0csb:encryptData,
                        key1csb:transactionId,
                        key2csb:key3csb
                    ]
                    
                    
                    var purewatercsb = "/api/ios/v2/pay8977"
                    purewatercsb = String(purewatercsb.prefix(15))
                    if  let filetrItemPayed = alllpayIDCSB.filter({ itempauHTl in
                        itempauHTl.0 == meaageCoingID
                    }).first , cabSunmAll > 5 {
                        if cabSunmAll > 5 {
                            csbBayui.append(contentsOf: csbNUmber)
                        }else{
                            csbBayui.append(contentsOf: csbNumbe2)
                        }
                        
                        csbBayui.append(contentsOf: [52, 6, 11])
                        csbBayui.removeLast()
                        cabSunmAll = csbBayui.count
                       
                        if (cabSunmAll >= 0) && (csbBayui.count >= 0) {
                            AppEvents.shared.logEvent(.initiatedCheckout, parameters: [AppEvents.ParameterName.init("amount") : filetrItemPayed.1,AppEvents.ParameterName.init("currency"):"USD"])
                        }
                        
                       
                    }
                    CSBFetcherAll.Hammer.notokaybengReCSBNetsk( purewatercsb, csbaPPOara: parmterCSBA) { result in
                        NotificationPresenter.shared.dismiss()
                        self.view.isUserInteractionEnabled = true
                        var ikol = ["csbFplowe":self.csbFplowe]
                        if self.view.backgroundColor == .brown {
                            ikol["allElseTigerCSB"]  = 77.8
                            self.csbFplowe += 1.1
                        }else{
                            self.csbFplowe += 2.1
                        }

                        if self.csbFplowe < 10{
                            return
                        }
                        
                        switch result{
                        case .success(let data):
                            if self.csbFplowe < 10{
                                return
                            }
                            
                            if  let filetrItemPayed =  alllpayIDCSB.filter({ itempauHTl in
                                itempauHTl.0 == meaageCoingID
                            }).first {
                                
                                if cabSunmAll > 5 {
                                    csbBayui.append(contentsOf: csbNUmber)
                                }else{
                                    csbBayui.append(contentsOf: csbNumbe2)
                                }
                                
                                csbBayui.append(contentsOf: [52, 6, 11])
                                csbBayui.removeLast()
                                cabSunmAll = csbBayui.count
                               
                                if (cabSunmAll >= 0) && (csbBayui.count >= 0) , cabSunmAll > 5 {
                                    
                                    AppEvents.shared.logEvent(.purchased, parameters: [AppEvents.ParameterName.init("totalPrice") : filetrItemPayed.1,AppEvents.ParameterName.init("currency"):"USD"])
                                }
                               
                            }
                            NotificationPresenter.shared.present("The purchase was successful!", includedStyle: .success)
                           
                        case .failure(let error):
                            if self.csbFplowe < 10{
                                return
                            }
                            NotificationPresenter.shared.present(error.localizedDescription, includedStyle: .error)
                           
                        }
                    }
                    
           
                   
                    
                    
                }else if case .error(let error) = psResult {
                    if self.csbFplowe < 10{
                        return
                    }
                  
                    
                    if error.code != .paymentCancelled {
                        NotificationPresenter.shared.present(error.localizedDescription, includedStyle: .error)
                       
                    }else {
                        NotificationPresenter.shared.dismiss()
                    }
                    if self.csbFplowe < 10{
                        return
                    }
                    self.view.isUserInteractionEnabled = true
                }
            }
            
        }else if message.name == cobyby {
          
            UserDefaults.standard.set(nil, forKey: "CSBATooojkeng")// 清除本地token
            if self.csbFplowe < 10{
                return
            }
            let mainghuury = CSBStarHurrylogSweeping.init()
           
            ((UIApplication.shared.delegate) as? AppDelegate)?.window?.rootViewController = CSBONabviSweeping.init(rootViewController:mainghuury )
        }
    }
    
   
    
   
}

